package com.powerunion.datacollection.service;

import java.sql.Connection;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.BsResponse;
import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.SubmissionWorkItemDao;
import com.powerunion.datacollection.model.ActivityInfo;
import com.powerunion.datacollection.model.ApproveActivityInstance;
import com.powerunion.datacollection.model.SubmissionWorkItem;
import com.powerunion.util.log.LogHelper;

public class SubmissionWorkItemManager {
	private static Logger logger = LogHelper.getInstance().getLogger(
			SubmissionWorkItemManager.class);
	private SubmissionWorkItemDao dao = null;

	public SubmissionWorkItemManager() {
		super();
		this.dao = (SubmissionWorkItemDao) DaoFactory.getInstance().getDao(
				SubmissionWorkItemDao.class);
	}

	public boolean save(ActivityInfo activityInfo,String formId,Connection conn) throws Exception {
		//参数为空
		if(StringUtils.isEmpty(formId)) {
			String[] args = { "formId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter formId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		if(activityInfo == null) {
			String[] args = { "activityInfo" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter activityInfo NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		if(conn == null) {
			String[] args = { "conn" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter conn NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		return dao.save(activityInfo, formId, conn);
	}
	
	public String findSubmissionWorkByUser(String userCode)throws Exception{
		//参数为空
		if(StringUtils.isEmpty(userCode)) {
			String[] args = { "userCode" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter userCode NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		List cts = this.dao.findSubmissionWorkByUser(userCode);
		JSONArray jsonArr = JSONArray.fromObject(cts);
		String result = "{results:"+jsonArr+"}";
		return result;
	}

	public boolean updateState(int state,String actId) throws Exception{
		//参数为空
		if(StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		return this.dao.updateState(state, actId);
	}
	
	public boolean updateState4User(int state,String id) throws Exception {
		//参数为空
		if(StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.updateState4User(state, id);
	}
	
	/**
	 * 提交报送数据
	 * @param actId 报送环节id
	 * @return
	 * @throws Exception
	 */
	public String submission(String actId,String submissionWorkId,String formId,String nextActivityId) throws Exception{
		//参数为空
		if(StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		if(StringUtils.isEmpty(nextActivityId)) {
			String[] args = { "nextActivityId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter nextActivityId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		String result = "";
		boolean flag = false;
		//判断该任务是否已经完成或被隐藏
		flag = this.dao.iSubWorkCommit(submissionWorkId);
		if(flag){//该任务是否被隐藏或已经完成
			result = "该任务已经结束！不能提交！";
			return result;
		}
		
		//需要判断环节类型来根据规则是否提交该上报数据
		boolean ipermit = this.dao.submissionRule(actId);
		if(ipermit){//允许
			int subType = this.getActivityType(actId);
			String subWorkIds = "";
			if(subType == Constants.SUBMISSION_TYPE_MULTI){//多人类型，则保存所有的报送任务id
				subWorkIds = this.dao.getActAllSubWorkIds(actId); 
			}else if(subType == Constants.SUBMISSION_TYPE_SINGLE){//单人类型，则只保存当前提交的报送任务id
				subWorkIds = ";"+submissionWorkId+";";//数据库数据格式为";id;"
			}
			ActivityManager am = new ActivityManager();
			//根据提交数据的采集步骤id得到上级的审批步骤
			ApproveActivityInstance parentActivity = am.getParentActivity(actId);
			ApproveActivityInstance aai = am.getApproveActivityInstance(nextActivityId);

			aai.setSubmiUser(subWorkIds);
			aai.setPreActivityId(actId);
			aai.setPreActivityType(Constants.COLLECTION_STEP_TYPE);
			
			ApproveWorkItemManager aim = new ApproveWorkItemManager();
			//如果之前已经有审批过 属于是要求被重新填写再提交的，则把先前的审批任务隐藏，重新生成新的任务
			aim.hideAllApproveWork(actId);

			flag = aim.initApproveWork(aai,formId);
			
			if(flag){//提交成功，则更新采集步骤状态
				if(subType == Constants.SUBMISSION_TYPE_SINGLE){
					//如果该采集步骤是单人类型而有设了多个采集人，又因为只会有一个人提交数据，所以把该采集步骤的其他非提交人的任务隐藏掉
					this.dao.updateState(Constants.SUBMISSION_HIDE, actId);
					//然后设置当前这个提交人的状态为等待审批
					flag = this.dao.updateState4User(Constants.SUBMISSION_WAIT4Approve, submissionWorkId);
				}else{
					flag = this.dao.updateState4User(Constants.SUBMISSION_WAIT4Approve, submissionWorkId);
					flag = this.dao.updateState(Constants.SUBMISSION_WAIT4Approve, actId);
				}
				 //更新流程实例中该步骤的状态
				ActivityManager activityManager = new ActivityManager();
				if(!parentActivity.getActivityId().equals(aai.getActivityId())){
					//如果被略过的上级审批步骤只有一个采集步骤，则设置该审批步骤为隐藏
					int children = activityManager.getChildren( parentActivity.getActivityId()).size();
					if(children == 1){
						activityManager.updateActivityState(Constants.ACTIVITY_JUMP_HIDE, parentActivity.getActivityId());
					}
					activityManager.reconfigActivityPosition(nextActivityId, actId);
				}
				activityManager.updateActivityState(Constants.ACTIVITY_WAIT, actId);
				result = "";
			}else{
				result = "提交数据失败！";
			}
		}else{
			int acivityType = this.dao.getActivityType(actId);
			if(acivityType == Constants.SUBMISSION_TYPE_SINGLE){
				result = "其他人已经提交了该采集数据！";
			}else if(acivityType ==  Constants.SUBMISSION_TYPE_MULTI){
				flag = this.dao.updateState4User(Constants.SUBMISSION_SYNCHRO_WAIT, submissionWorkId);
				result = "";
			}
		}
	
		return result;
	}
	
	public BsResponse submission4SubTbl(String actId,String submissionWorkId,String formId,String nextActivityId) throws Exception{
		//参数为空
		if(StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		if(StringUtils.isEmpty(nextActivityId)) {
			String[] args = { "nextActivityId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter nextActivityId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		BsResponse rs = new BsResponse();

		boolean flag = false;
//		//判断该任务是否已经完成或被隐藏
//		flag = this.dao.iSubWorkCommit(submissionWorkId);
//		if(flag){//该任务是否被隐藏或已经完成
//			result = "该任务已经结束！不能提交！";
//			rs.setReturnFlag(BsResponse.FATAL_ERR_FLAG);
//			rs.setReturnMsg("该任务已经结束！不能提交！");
//			return rs;
//		}
		
		//需要判断环节类型来根据规则是否提交该上报数据
		boolean ipermit = this.dao.submissionRule(actId);
		if(ipermit){//允许
			int subType = this.getActivityType(actId);
			String subWorkIds = "";
			if(subType == Constants.SUBMISSION_TYPE_MULTI){//多人类型，则保存所有的报送任务id
				subWorkIds = this.dao.getActAllSubWorkIds(actId); 
			}else if(subType == Constants.SUBMISSION_TYPE_SINGLE){//单人类型，则只保存当前提交的报送任务id
				subWorkIds = ";"+submissionWorkId+";";//数据库数据格式为";id;"
			}
			ActivityManager am = new ActivityManager();
			//根据提交数据的采集步骤id得到上级的审批步骤
			ApproveActivityInstance parentActivity = am.getParentActivity(actId);
			ApproveActivityInstance aai = am.getApproveActivityInstance(nextActivityId);

			aai.setSubmiUser(subWorkIds);
			aai.setPreActivityId(actId);
			aai.setPreActivityType(Constants.COLLECTION_STEP_TYPE);
			
			ApproveWorkItemManager aim = new ApproveWorkItemManager();
			//如果之前已经有审批过 属于是要求被重新填写再提交的，则把先前的审批任务隐藏，重新生成新的任务
			aim.hideAllApproveWork(actId);

			flag = aim.initApproveWork(aai,formId);
			
			if(flag){//提交成功，则更新采集步骤状态
				if(subType == Constants.SUBMISSION_TYPE_SINGLE){
					//如果该采集步骤是单人类型而有设了多个采集人，又因为只会有一个人提交数据，所以把该采集步骤的其他非提交人的任务隐藏掉
					this.dao.updateState(Constants.SUBMISSION_HIDE, actId);
					//然后设置当前这个提交人的状态为等待审批
					flag = this.dao.updateState4User(Constants.SUBMISSION_WAIT4Approve, submissionWorkId);
				}else{
					flag = this.dao.updateState4User(Constants.SUBMISSION_WAIT4Approve, submissionWorkId);
					flag = this.dao.updateState(Constants.SUBMISSION_WAIT4Approve, actId);
				}
				 //更新流程实例中该步骤的状态
				ActivityManager activityManager = new ActivityManager();
				if(!parentActivity.getActivityId().equals(aai.getActivityId())){
					//如果被略过的上级审批步骤只有一个采集步骤，则设置该审批步骤为隐藏
					int children = activityManager.getChildren( parentActivity.getActivityId()).size();
					if(children == 1){
						activityManager.updateActivityState(Constants.ACTIVITY_JUMP_HIDE, parentActivity.getActivityId());
					}
					activityManager.reconfigActivityPosition(nextActivityId, actId);
				}
				activityManager.updateActivityState(Constants.ACTIVITY_WAIT, actId);
				rs.setReturnFlag(BsResponse.SUCCEED_FLAG);
			}else{
				rs.setReturnFlag(BsResponse.FATAL_ERR_FLAG);
				rs.setReturnMsg("提交数据失败！");
			}
		}else{
			int acivityType = this.dao.getActivityType(actId);
			if(acivityType == Constants.SUBMISSION_TYPE_SINGLE){
				rs.setReturnFlag(BsResponse.FATAL_ERR_FLAG);
				rs.setReturnMsg("其他人已经提交了该采集数据！");
			}else if(acivityType ==  Constants.SUBMISSION_TYPE_MULTI){
				flag = this.dao.updateState4User(Constants.SUBMISSION_SYNCHRO_WAIT, submissionWorkId);
				rs.setReturnFlag(BsResponse.SUCCEED_FLAG);
			}
			
		}
	
		return rs;
	}
	
	
	public boolean suspendSubmissionWork(String procId) throws Exception {
		//参数为空
		if(StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		return this.dao.suspendSubmissionWork(procId);
	}
	
	public boolean resumeSubmissionWork(String procId) throws DaoException {
		//参数为空
		if(StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.resumeSubmissionWork(procId);
	}
	
	public List findSubmissionWorkIdByActivityId(String activityId) throws DaoException {
		//参数为空
		if(StringUtils.isEmpty(activityId)) {
			String[] args = { "activityId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter activityId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.findSubmissionWorkIdByActivityId(activityId);
	}
	
	public int getActivityType(String actId) throws DaoException{
		//参数为空
		if(StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getActivityType(actId);
	}
	/**
	 * 查找已办采集任务
	 * @param userCode
	 * @return
	 * @throws DaoException
	 */
	public String findCompleteSubmissionWorkByUser(String userCode)throws DaoException {
		//参数为空
		if(StringUtils.isEmpty(userCode)) {
			String[] args = { "userCode" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter userCode NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		List cts = this.dao.findCompleteSubmissionWorkByUser(userCode);
		JSONArray jsonArr = JSONArray.fromObject(cts);
		String result = "{results:"+jsonArr+"}";
		return result;
		
	}
	
	public List getAllSubWorksByAct(String procId,String actId,int currentOrParrent) throws Exception{
		//参数为空
		if(StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.getAllSubWorksByAct(procId,actId,currentOrParrent);
	}
	
	public String findAllSubmissionWorkByUser(String userCode)
	throws Exception {
		//参数为空
		if(StringUtils.isEmpty(userCode)) {
			String[] args = { "userCode" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter userCode NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		List cts =  this.dao.findAllSubmissionWorkByUser(userCode);
		JSONArray jsonArr = JSONArray.fromObject(cts);
		String result = "{results:"+jsonArr+"}";
		return result;
		
	}
	
	public SubmissionWorkItem getByKey(String id) throws Exception {
		//参数为空
		if(StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getByKey(id);
	}
	
	/**
	 * 保存一条报送任务
	 * 主要用于审批步骤整合所有的上报的数据成一份数据的时候
	 * @param userCode
	 * @param activityInfo
	 * @param formId
	 * @return
	 * @throws DaoException
	 */
	public boolean initSubWork(String userCode, ActivityInfo activityInfo,
			String formId) throws DaoException {
		//参数为空
		if(StringUtils.isEmpty(userCode)) {
			String[] args = { "userCode" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter userCode NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		//参数为空
		if(StringUtils.isEmpty(formId)) {
			String[] args = { "formId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter formId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		//参数为空
		if(activityInfo == null) {
			String[] args = { "activityInfo" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter activityInfo NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
			
		return this.dao.initSubWork(userCode, activityInfo, formId);
	}
	/**
	 * 转发任务
	 * @param swi
	 * @param receiveUsers
	 * @return
	 * @throws DaoException
	 */
	public boolean saveByTransmit(SubmissionWorkItem swi,String receiveUsers) throws DaoException {
		//参数为空
		if(swi == null) {
			String[] args = { "swi" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter swi NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		//参数为空
		if(StringUtils.isEmpty(receiveUsers)) {
			String[] args = { "receiveUsers" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter receiveUsers NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.saveByTransmit(swi, receiveUsers);
		
	}

	public List getAllSubWorksByAct(String procId, String actId,
			int currentOrParrent,int actType) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		// 参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		return this.dao.getAllSubWorksByAct(procId, actId, currentOrParrent, actType);
	}
	/**
	 * 判断该报送任务是否已经提交
	 * @param id
	 * @return
	 * @throws DaoException
	 */
	public boolean iSubWorkCommit(String id) throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.iSubWorkCommit(id);
	}
	
	public int getState(String id) throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getState(id);
	}
	
}
